/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springblade.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.constant.SecurityConstants;
import org.springblade.common.tool.AuthUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhouhong
 * @date 2018/7/4
 * 验证码处理
 */
@Component
@AllArgsConstructor
@Slf4j
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory{
	private final ObjectMapper objectMapper;
	private final RedisTemplate redisTemplate;

	@Override
	public GatewayFilter apply(Object config) {
		return new InnerFilter(config);
		};
	private class InnerFilter implements GatewayFilter, Ordered {
		private Object config;

		InnerFilter(Object config) {
			this.config = config;
		}

		@Override
		public int getOrder() {
			return -100;
		}
		/**
		 * 检查code
		 *
		 * @param request
		 */
		@SneakyThrows
		private void checkCode(ServerHttpRequest request) {
			String code = request.getHeaders().getFirst(AuthUtils.CAPTCHA_HEADER_CODE);
			String key = request.getHeaders().getFirst(AuthUtils.CAPTCHA_HEADER_KEY);
			// 获取验证码
			String redisCode = String.valueOf(ValidateCodeGatewayFilter.this.redisTemplate.opsForValue().get(CacheNames.CAPTCHA_KEY + key));

			// 判断验证码
			if (code == null || !StrUtil.equalsIgnoreCase(redisCode, code)) {
				ValidateCodeGatewayFilter.this.redisTemplate.delete(key);
				throw new RuntimeException(AuthUtils.CAPTCHA_NOT_CORRECT);
			}
			ValidateCodeGatewayFilter.this.redisTemplate.delete(key);
		}

		@Override
		public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
			ServerHttpRequest request = exchange.getRequest();

			// 不是登录请求，直接向下执行
			if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
				, SecurityConstants.OAUTH_TOKEN_URL)) {
				return chain.filter(exchange);
			}

			// 刷新token，直接向下执行
			String grantType = request.getQueryParams().getFirst("grantType");
			String tenantId = request.getQueryParams().getFirst("tenantId");
			if (!StrUtil.equals(SecurityConstants.PASSWORD, grantType) || !StrUtil.equals("000000",tenantId)) {
				return chain.filter(exchange);
			}

			// 终端设置不校验， 直接向下执行
			try {
				//校验验证码
				checkCode(request);
			} catch (Exception e) {
				ServerHttpResponse response = exchange.getResponse();
				response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
				try {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("code",400);
					jsonObject.put("msg",e.getMessage());
					return response.writeWith(Mono.just(response.bufferFactory()
						.wrap(ValidateCodeGatewayFilter.this.objectMapper.writeValueAsBytes(
							jsonObject))));
				} catch (JsonProcessingException e1) {
					log.error("对象输出异常", e1);
				}
			}
			return chain.filter(exchange);
		}
	}
}
